<template>
  <SysDialog :title="dialogBasic.title" :width="dialogBasic.width" :height="dialogBasic.height"
    :show-footer="dialogBasic.showFooter" :visible="dialogBasic.visible" :margin-top="dialogBasic.marginTop"
    @on-close="onClose" @on-confirm="onConfirm">
    <template v-slot:content>

      <el-form ref="ruleFormRef" :model="userForm" :rules="rules" label-width="120px" class="demo-ruleForm" status-icon>

        <el-form-item label="用户账号" prop="username">
          <el-input v-model="userForm.username" />
        </el-form-item>
        <el-form-item label="用户姓名" prop="nickname">
          <el-input v-model="userForm.nickname" />
        </el-form-item>
        <el-form-item label="手机号码" prop="mobile">
          <el-input v-model="userForm.mobile" />
        </el-form-item>
        <el-form-item label="用户邮箱" prop="email">
          <el-input v-model="userForm.email" />
        </el-form-item>
        <el-form-item label="是否启用" prop="enabled">
          <el-select v-model="userForm.enabled" placeholder="请选择用户是否启用">
            <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="所在地-省" prop="provinceCode">
          <el-select v-model="userForm.provinceCode" @change="proChange" placeholder="请选择所在省份">
            <el-option v-for="item in province" :key="item.id" :label="item.dictItemName" :value="item.dictItemCode" />
          </el-select>
        </el-form-item>
        <el-form-item label="所在地-市" prop="cityCode">
          <el-select v-model="userForm.cityCode" @change="proChange1" placeholder="请选择所在市">
            <el-option v-for="item in selectProvinceCity" :key="item.id" :label="item.dictItemName"
              :value="item.dictItemCode" />
          </el-select>
        </el-form-item>

        <el-form-item label="详细地址" prop="adress">
          <el-input v-model="userForm.adress" />
        </el-form-item>
        <el-form-item label="简介" prop="blurb">
          <el-input v-model="userForm.blurb" />
        </el-form-item>

      </el-form>
    </template>
  </SysDialog>
</template>
<script setup lang='ts'>
import { ref, reactive } from "vue"
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage } from 'element-plus'
import { storeToRefs } from "pinia"
import { useColorStore } from "@/store/common"
import useInstance from '@/hooks/useInstance';
import { accountSaveOrUpdateApiPost } from "@/api/userMangement"
defineOptions({
  name: 'addUserAndEdit'
})

const provinceData = useColorStore()
const { province, selectProvinceCity } = storeToRefs(provinceData)
const { filterData } = provinceData
const emit = defineEmits(['refresh','searchEdit'])
const { global } = useInstance();
const ruleFormRef = ref<FormInstance>()
const dialogBasic = ref({
  title: "新建用户",
  visible: false,
  width: 600,
  height: 450,
  showFooter: true,
  marginTop: "10vh",
})
const options = [
  {
    label: "启用",
    value: "Y"
  },
  {
    label: "禁用",
    value: "N"
  }
]
const userForm = reactive<any>({
  username: null, //用户账号
  nickname: null, //姓名
  mobile: null, // 手机号
  email: null, //邮箱
  enabled: null, //是否启用
  provinceCode: null, // 所在地-省
  provinceName: null, // 所在地-省
  cityCode: null, // 所在地-市
  cityName: null, // 所在地-市
  adress: null, // 所在地-详细地址
  blurb: null, //简介

})
const rules = reactive<FormRules>({
  provinceCode: [
    {
      required: true,
      trigger: 'blur',
      message: "请选择用户所在地-省"
    },
  ],
  cityCode: [
    {
      required: true,
      trigger: 'blur',
      message: "请选择用户所在地-市"
    },
  ],

  username: [
    {
      required: true,
      trigger: 'blur',
      message: "请输入用户姓名"
    },
    {
      pattern:/^[0-9a-z]*$/,
      message: "只能输入小写字母和数字"
    }
  ],
  nickname: [
    {
      required: true,
      trigger: 'blur',
      message: "请输入用户真实姓名"
    },
  ],
  mobile: [
    {
      required: true,
      trigger: 'blur',
      message: "请输入用户手机号"
    },
    {
      trigger: 'blur',
      message: "请输入正确的手机号",
      pattern: /^1[3-9]\d{9}$/
    }
  ],
  email: [
    {
      required: true,
      trigger: 'blur',
      message: "请输入用户邮箱"
    },
    {
      pattern:/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/,
      message: "请输入正确的邮箱格式"
    }
  ],
  enabled: [
    {
      required: true,
      trigger: 'blur',
      message: "请选择用户是否启用"
    },
  ],
})
//显示弹框
const show = (type: string, row?: any) => {
  selectProvinceCity.value =null

  resetForm()
  global.$resetForm(ruleFormRef.value, userForm)
  if (type === 'add') {
    dialogBasic.value.title = "新建用户"
  } else {
    dialogBasic.value.title = "用户编辑"
    global.$objCopy(userForm, row)
    // 需要查询
    filterData(1, null, row.provinceCode)
  }
  dialogBasic.value.visible = true
}
const onClose = () => {
  //数据清楚
  selectProvinceCity.value =null

  dialogBasic.value.visible = false
  Object.keys(userForm).forEach(it => userForm[it] = null)
}

const onConfirm = async () => {
  await ruleFormRef.value?.validate(async isOk => {

    if (isOk) {
      try {
        const res = await accountSaveOrUpdateApiPost(userForm)
        if (res.code == 20000) {
          emit('refresh')
          if(userForm.id ){
            emit('searchEdit')
          }else{
            emit('refresh')
          }
          onClose()
          ElMessage({
            type: "success",
            message: userForm.id ? "用户编辑成功 请重试！" : "用户新增成功 "
          })
        }

      } catch (error) {
        ElMessage({
          type: "error",
          message: userForm.id ? "用户编辑失败 请重试！" : "用户新增失败"
        })
      }
    } else {
      ElMessage({
        type: "error",
        message: userForm.id ? "用户编辑失败 请重试！" : "用户新增失败 请重试！"
      })
    }
  })


}

const resetForm = () => {
  ruleFormRef.value?.resetFields()
}
const proChange = (val: any) => {

  province.value.some(item => {
    if (val == item.dictItemCode) {
      filterData(1, item.id)
      userForm.provinceName = item.dictItemName
      userForm.cityName = null
      userForm.cityCode = null
      return
    }
  })

}
const proChange1 = (val: any) => {
  console.log(val); // 没有数据 马上测试
  selectProvinceCity.value.some(item => {
    if (val == item.dictItemCode) {
      userForm.cityName = item.dictItemName
      return
    }
  })
}
defineExpose({
  show
})
</script>


<style lang='scss' scoped></style>
